import {nodeResolve} from '@rollup/plugin-node-resolve';
import typescript from '@rollup/plugin-typescript';
import commonjs from '@rollup/plugin-commonjs';
import terser from '@rollup/plugin-terser';
import cleanup from 'rollup-plugin-cleanup';
// import { visualizer } from "rollup-plugin-visualizer";
import {readdirSync} from 'fs';
import {resolve, extname, basename} from 'path';

// 自动读取 src 文件夹中的所有 .ts 文件
const inputFiles = readdirSync('./src')
.filter(file => extname(file) === '.ts')
.reduce((entries, file) => {
  const name = basename(file, '.ts');
  entries[name] = resolve('./src', file);
  return entries;
}, {});

const dirPath = 'dist';
// ESM 插件
const esmPlugins = [
  // 解析 Node 模块
  nodeResolve({
    resolveOnly: ['lodash-es', 'decimal.js', 'pinyin-pro'],
  }),
  commonjs(), // 转换 CommonJS 模块为 ESM
  typescript({
    tsconfig: './tsconfig.json',
  }),
  terser(), // 压缩代码
  cleanup(), // 清理输出文件中的 BOM 和多余的空格等
  // visualizer({
  //   emitFile: true,
  //   filename: "stats.html",
  // }),
];
// CJS 插件
const cjsPlugins = [
  // 解析 Node 模块
  nodeResolve({
    resolveOnly: ['lodash-es', 'decimal.js', 'pinyin-pro'],
  }),
  typescript({
    tsconfig: './tsconfig.json'
  }),
  terser(),
  cleanup(),
];

export default [
  // ESM 输出
  {
    input: inputFiles,
    output: {
      dir: dirPath,
      format: 'esm',
      entryFileNames: '[name].js',
      sourcemap: false,
    },
    plugins: esmPlugins,
    external: ['dayjs'],
  },
  // CJS 输出
  {
    input: inputFiles,
    output: {
      dir: dirPath,
      format: 'cjs',
      entryFileNames: '[name].cjs.js',
      exports: 'named',
      sourcemap: false,
    },
    plugins: cjsPlugins,
    external: ['dayjs'],
  }
];
